package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 自动填充类
 *
 * @author heyingcheng
 * @date 2025/7/20
 */
@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {

    private final Logger log = LoggerFactory.getLogger(MetaObjectHandlerConfig.class);

    /**
     * 设置系统默认ID
     */
    public static final String CREATE_BY = "createBy";
    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_BY = "updateBy";
    public static final String UPDATE_TIME = "updateTime";
    public static final String DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (Objects.nonNull(loginUser)) {
                setFieldValByName(DEPT_ID, loginUser.getDeptId(), metaObject);
                setFieldValByName(CREATE_BY, loginUser.getUsername(), metaObject);
                setFieldValByName(UPDATE_BY, loginUser.getUsername(), metaObject);
            }
        } catch (ServiceException e) {
            log.error("无法获取登录用户信息, 请检查是否登录");
        }

        LocalDateTime now = LocalDateTime.now();
        setFieldValByName(CREATE_TIME, now, metaObject);
        setFieldValByName(UPDATE_TIME, now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (Objects.nonNull(loginUser)) {
                setFieldValByName(UPDATE_BY, loginUser.getUsername(), metaObject);
            }
        } catch (ServiceException e) {
            log.error("无法获取登录用户信息, 请检查是否登录");
        }

        setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
    }

}
